<?php 
namespace App\Services\User;

use App\Facades\Infra\User\WeightManage;
use App\Exceptions\CreateDataException;
use App\Facades\Infra\User\WeChatManage;
use App\Facades\Infra\User\UserManage;
use DB;
use Session;

class WeightService{

	public function createRecord($data){
		
		$user = $this->getUser();

		$conditions = [
			'wechat_user_id' => $user->id
		];

		if(count(WeightManage::getRecordToDay($conditions)) > 0){
			throw new CreateDataException('今日已经存在数据');
		}

		$data['wechat_user_id'] = $user->id;

		$updateData = [
			'weight' => $data['weight'],
			'bmi' => $this->countBmi($data['weight'],$this->getHegithInSession())
		];

		DB::transaction(function() use ($data,$updateData,$user){

			WeightManage::createWeight($data);

			UserManage::updateUserInfo($user->wechatUserInfo->id,$updateData);
		});
	}

	public function getRecordById($data){

		$id=$data['id'];
		
		return WeightManage::getRecordById($id);
	}

	public function updateTodayRecord($data){

		$user = $this->getUser();

		$conditions = [
			'id' => $data['id'],
			'wechat_user_id' => $user->id
		];

		if(count(WeightManage::getRecordToDay($conditions)) < 1){
			throw new CreateDataException('只能修改当天数据');
		}

		$updateData = [
			'weight' => $data['weight'],
			'bmi' => $this->countBmi($data['weight'],$this->getHegithInSession())
		];

		DB::transaction(function() use($data,$updateData,$user){

			WeightManage::updateRecord($data['id'],$data);

			UserManage::updateUserInfo($user->wechatUserInfo->id,$updateData);
		});
	}

	public function todayHasCreate(){
		$userId = $this->getUser()->id;

		$conditions = [
			'wechat_user_id' => $userId
		];

		$weight = WeightManage::getRecordToDay($conditions);

		if(count($weight) > 0){
			return $weight[0];
		}

		return null;
	}

	public function getHegithInSession(){

		if(Session::has('user.height')){
			return Session::get('user.height');
		}

		Session::put('user.height',$this->getUser()->wechatUserInfo->height);

		return Session::get('user.height');
	}

	public function getWeights(){
		$user = $this->getUser();

		$conditions['wechat_user_id'] = $user->id;

		return WeightManage::getWeights($conditions)->get();
	}

	private function getUser(){
		$openid = session('wechat.oauth_user')->getId();

		$conditions['openid'] = $openid;

		$wechatUser = WeChatManage::getUserInfo($conditions);

		return $wechatUser;
	}

	public function countBmi($weight,$height){
		$meterHeight = $height/100;

		$bmi = $weight/($meterHeight*$meterHeight);

		return round($bmi,1);
	}

}